<?php
namespace app\controllers;
require_once "../common/corelib/wxPay/lib/WxPay.Api.php";
require_once '../common/corelib/wxPay/lib/WxPay.Notify.php';
require_once '../common/corelib/wxPay/example/WxPay.JsApiPay.php';
use app\common\corelib\CacheHelper;
use app\common\HttpCurl;
use app\logic\CommonLogic;
use app\logic\DeviceLogic;
use app\logic\OrderLogic;
use app\logic\PlayGoodsLogic;
use app\logic\ShopLogic;
use app\logic\UserLogic;
use app\models\Goods;
use app\models\Order;
use Yii;

use WxPayUnifiedOrder;
use WxPayApi;
use JsApiPay;

use app\logic\PayNotifyCallBack;


class OrderController extends BaseController
{

	public function actionIndex()
	{
            echo "index";
	}

	public function actionScanCode(){
        $manager_code = $this->getQueryparams('manager_code','');
        $cancel_num = $this->getQueryparams('cancel_num',0);
        $orderLogic = new OrderLogic();
        $result = $orderLogic->cancelScanCode($manager_code,$this->user_id,$cancel_num);
        if($result){
            $this->response($result);
        }else{
            $this->error('200003',"该订单不能核销");
        }

    }

    public function actionCancelScanCode(){
        $userLogic = new UserLogic();
        $manager_code = $this->getQueryparams('manager_code','');
        $user = $userLogic->getUser($this->user_id);
        $manager = $userLogic->getUserByManagerCode($manager_code);
        $this->response(['num'=>$user->current_num,'manager_name'=>$manager['manager_name'],'shop_name'=>$manager['shop_name'],'shop_pic'=>$manager['shop_pic']]);
    }

    /**
     * 保存订单
     * @apiDescription   by Jim
     * @api              {post} /order/submit-order 保存订单
     * @apiName          submit-order
     * @apiVersion       1.0.0
     * @apiParam {int} type 0:卡券，1：商品
     * @apiParam {int} goods_play_id 卡券或者商品id
     * @apiParam {int} shop_id 自提商店id
     * @apiParam {string} openid openid
     * @apiParam {int} access_token 登录后获取的access_token
     * @apiGroup         Order
     * @apiSampleRequest /order/submit-order?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {
    appid
    timeStamp
    nonceStr
    prepay_id
    signType("MD5")
    paySign
     * order_no 订单号
      }
     * @apiError         200001
     */
	public function actionSubmitOrder(){
        //$user_id = $this->getQueryparams('user_id',0);
        $type = $this->getQueryparams('type',0);
        $openid = $this->getQueryparams('openid','');
        $goods_play_id = $this->getQueryparams('goods_play_id',0);
        $playGoodsLogic = new PlayGoodsLogic();
        $shop_id = $this->getQueryparams('shop_id',0);

        $deviceLogic = new DeviceLogic();
        $play_num = $this->getQueryparams('play_num',0);
        $play_money = $this->getQueryparams('play_money',0);

        $userLogic = new UserLogic();
        $user = $userLogic->getUser($this->user_id);
        if($user->type!=0)
            $this->error('200008',"您不是普通用户，不能下单");
        $ext_price = 0;
        if($type==1){
            $goods = $playGoodsLogic->getGoods($goods_play_id);
            $current_num = 0;
            $expire_time = date('Y-m-d', strtotime("+".$goods['effective_days']." day"));
            $body = $goods['goods_name'];
            $price = $goods['price'];
        }elseif($type==0){
            $play = $playGoodsLogic->getPlay($goods_play_id);
            if($play['type']){
                $current_num = $play['num'];
                $ext_price = $play['ext_price'];
            }else{
                $current_num = 1;
            }
            $expire_time = date('Y-m-d', strtotime("+".$play['expire_time']." day"));
            $body = $play['play_name'];
            $price = $play['price'];
        }elseif($type==2){
            $device = $deviceLogic->getDeviceById($goods_play_id);
            $shopLogic = new ShopLogic();
            $manager = $shopLogic->getManager($device['shop_id']);
            if(!$manager){
                $this->error('2001009','此设备暂时无法使用在线支付');
            }
            $current_num = $play_num;
            $expire_time = date('Y-m-d');
            $body = '儿嬉摇摇车';
            $price = $play_money;
        }

        $orderLogic = new OrderLogic();
        $order_no = $orderLogic->createOrderNo();
        $order2 = Order::findOne(['order_no'=>$order_no]);
        while($order2){
            $order_no = $orderLogic->createOrderNo();
            $order2 = Order::findOne(['order_no'=>$order_no]);
        }
        $cancel_no = $orderLogic->createCancelNo();
        $order3 = Order::findOne(['cancel_no'=>$cancel_no]);
        while($order3){
            $cancel_no = $orderLogic->createCancelNo();
            $order3 = Order::findOne(['cancel_no'=>$cancel_no]);
        }
        /*$order_no = $orderLogic->createOrderNo();
        $cancel_no = $orderLogic->createCancelNo();*/
        $orderresult = $orderLogic->saveOrder($order_no,$cancel_no,$type,$goods_play_id,$price,$current_num,$expire_time,$this->user_id,$shop_id,$ext_price);


        if($orderresult){
            $result = $this->_wxPay($body,$order_no,$price,$this->user_id,$openid);
            if($result['return_code']=='SUCCESS'){
                $tools = new JsApiPay();
                $jsApiParameters = $tools->GetJsApiParameters($result);
                $jsApiParameters_arr = json_decode($jsApiParameters,true);
                $jsApiParameters_arr['order_no'] = $order_no;
                $this->response($jsApiParameters_arr);
            }else{
                $this->error('200001',$result['return_msg']);
            }
        }else{
            $this->error('200001',"FAIL");
        }

    }

    private function _wxPay($body,$order_no,$price,$user_id,$openid){

        //require_once "WxPay.JsApiPay.php";
        //require_once 'log.php';
        $input = new WxPayUnifiedOrder();
        $input->SetBody($body);
        $input->SetAttach("none");
        $input->SetOut_trade_no($order_no);
        $input->SetTotal_fee($price*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("none");
        $input->SetNotify_url("http://api.buerxi.com/order/notify");
        $input->SetTrade_type("JSAPI");
        $userLogic = new UserLogic();
        $user = $userLogic->getUser($user_id);
        //$input->SetOpenid($user->open_id);
        $input->SetOpenid($openid);
        $order = WxPayApi::unifiedOrder($input);
        return $order;
    }

    public function actionNotify(){
        $notify = new PayNotifyCallBack();
        $notify->Handle(false);
    }
    /**
     * 订单详情
     * @apiDescription   by Jim
     * @api              {post} /order/order-detail 订单详情
     * @apiName          order-detail
     * @apiVersion       1.0.0
     * @apiParam {string} order_no 订单号
     * @apiParam {string} access_token
     * @apiGroup         Order
     * @apiSampleRequest /order/order-detail?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {
    `order_id` int(11) NOT NULL AUTO_INCREMENT,
    `order_no` varchar(255) NOT NULL COMMENT '订单编号',（二维码编号）
    `type` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '订单类型：默认0，play类型，1,goods类型',
    `status` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '订单状态：0未支付,1已付款，2,已提货，3使用中，4已使用或已回收',
    `gp_id` int(11) unsigned NOT NULL COMMENT '商品或者体验券id',
    `current_num` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '体验卡或者体验券当前有效次数，商品为0，体验券为0或者1，体验卡为0+',
    `price` decimal(10,2) unsigned NOT NULL,
    `order_time` datetime NOT NULL COMMENT '下单时间',
    `pay_time` datetime DEFAULT NULL COMMENT '支付时间',
    `expire_time` date NOT NULL COMMENT '有效时间',
    `user_id` int(11) unsigned NOT NULL COMMENT ' 购买用户id',
    `shop_id` int(11) unsigned DEFAULT NULL COMMENT '自提点商店',
     * goods(play):{goods_name(play_name)商品名或者卡券名，通过type判断}
     is_card 是play类型的体验卡类型
     phone 购买者电话
    }
     * @apiError         none
     */
    public function actionOrderDetail(){
        $order_no = $this->getQueryparams('order_no',0);
        $cancel_no = $this->getQueryparams('cancel_no','');
        $cancel_num = $this->getQueryparams('cancel_num',1);
        if(strlen($cancel_no)>8){
            $cancel_notemp = $cancel_no;
            $cancel_num = substr($cancel_notemp,8);
            $cancel_no = substr($cancel_no,0,8);
        }
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrder($order_no);
        $playGoodsLogic = new PlayGoodsLogic();
        if($order['type']==2){

        }
        elseif($order['type']==1){
            $order['goods'] = $playGoodsLogic->getGoods($order['gp_id']);
            $order['is_card']=0;
        }else{
            $order['play'] =$playGoodsLogic->getPlay($order['gp_id']);
            $order['is_card']=$order['play']['type'];
            if($order['play']['type']){
                $userLogic = new UserLogic();
                $user = $userLogic->getUser($order['user_id']);
                $order['play']['current_num'] = $user->current_num;
                $order['current_num'] = $cancel_num;
            }

        }
        $this->response($order);
    }
    /**
     * 扫码后订单详情
     * @apiDescription   by Jim
     * @api              {post} /order/get-cancel-detail 扫码后订单详情
     * @apiName          get-cancel-detail
     * @apiVersion       1.0.0
     * @apiParam {string} order_no 订单号
     * @apiParam {string} access_token
     * @apiGroup         Order
     * @apiSampleRequest /order/get-cancel-detail?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {
    `order_id` int(11) NOT NULL AUTO_INCREMENT,
    `order_no` varchar(255) NOT NULL COMMENT '订单编号',（二维码编号）
    `type` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '订单类型：默认0，play类型，1,goods类型',
    `status` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '订单状态：0未支付,1已付款，2,已提货，3使用中，4已使用或已回收',
    `gp_id` int(11) unsigned NOT NULL COMMENT '商品或者体验券id',
    `current_num` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '体验卡或者体验券当前有效次数，商品为0，体验券为0或者1，体验卡为0+',
     `price` decimal(10,2) unsigned NOT NULL,
    `order_time` datetime NOT NULL COMMENT '下单时间',
    `pay_time` datetime DEFAULT NULL COMMENT '支付时间',
    `expire_time` date NOT NULL COMMENT '有效时间',
    `user_id` int(11) unsigned NOT NULL COMMENT ' 购买用户id',
    `shop_id` int(11) unsigned DEFAULT NULL COMMENT '自提点商店',
     * goods(play):{goods_name(play_name)商品名或者卡券名，通过type判断}
     * phone 购买者电话
     * shop_name 关联商店
    }
     * @apiError         none
     */
    public function actionGetCancelDetail(){
        $order_no = $this->getQueryparams('order_no','');
        $cancel_no = $this->getQueryparams('cancel_no','');
        $cancel_num = $this->getQueryparams('cancel_num',1);
        if(strlen($cancel_no)>8){
            $cancel_notemp = $cancel_no;
            $cancel_num = substr($cancel_notemp,8);
            $cancel_no = substr($cancel_no,0,8);
        }
        $userLogic = new UserLogic();
        $user = $userLogic->getUser($this->user_id);
        if($user->type!=2){
            $this->error('200002','请登录店长账户进行扫码');
        }
        $orderLogic = new OrderLogic();
        if(strpos($order_no,',')!==false){
            $order_no = explode(',',$order_no);
            $order_no = $order_no[0];
        }
        $order = $orderLogic->getOrder($order_no);
        $playGoodsLogic = new PlayGoodsLogic();
        if($order['type']==1){
            $order['goods'] = $playGoodsLogic->getGoods($order['gp_id']);
            $order['is_card']=0;
        }elseif($order['type']==2){
            $deviceLogic = new DeviceLogic();
            $order['device'] = $deviceLogic->getDeviceById($order['gp_id']);
        }else{
            $order['play'] =$playGoodsLogic->getPlay($order['gp_id']);
            $order['is_card']=$order['play']['type'];
            if($order['play']['type']){
                /*$userLogic = new UserLogic();
                $user = $userLogic->getUser($order['user_id']);
                $order['play']['current_num'] = $user->current_num;*/
                $order['play']['current_num'] = $cancel_num;
                $order['current_num'] = $cancel_num;

                $can_use = $orderLogic->getCanUseCard($order['user_id']);
                if($can_use){
                    $order['status'] = $can_use;
                }
            }
        }
        $shopLogic = new ShopLogic();
        $shop = $shopLogic->getManagerShop($this->user_id);
        $order['shop_name'] = $shop['shop_name'];
        $order['shop_id'] = $shop['shop_id'];
        $this->response($order);
    }

    /*public function actionPickUpOrder(){
        $order_no = $this->getQueryparams('order_no',0);
        $userLogic = new UserLogic();
        $user = $userLogic->getUser($this->user_id);
        if($user->type!=2){
            $this->error('200003','请登录店长账户进行提货操作');
        }
        $orderLogic = new OrderLogic();
        $result = $orderLogic->pickUpOrder($order_no,$this->user_id);
        if($result){
            $this->response();
        }else{
            $this->error('200003',"FAIL");
        }
    }*/
    /**
     * 核销卡券、提货、回收商品
     * @apiDescription   by Jim
     * @api              {post} /order/cancel-order 核销卡券、提货、回收商品
     * @apiName          cancel-order
     * @apiVersion       1.0.0
     * @apiParam {string} order_no 核销的订单no
     * @apiParam {int} type 类型：默认0为核销体验券，1为核销体验卡，2为提货商品，3为回收商品'
     * @apiParam {string} access_token
     * @apiGroup         Order
     * @apiSampleRequest /order/cancel-order?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {

    }
     * @apiError         200003 fail 200002 请登录店长账户进行核销
     */
    public function actionCancelOrder(){
        $cancel_no = $this->getQueryparams('cancel_no',0);
        $type = $this->getQueryparams('type',0);
        $cancel_num = $this->getQueryparams('cancel_num',0);
        $userLogic = new UserLogic();
        $user = $userLogic->getUser($this->user_id);
        if($user->type!=2){
            $this->error('200002','请登录店长账户进行核销');
        }
        $manager = $userLogic->getManager($this->user_id);
        if($manager['on_work']!=1){
            $this->error('200009','您没有上班，不能核销');
        }
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderByCancelNo($cancel_no);
        if($order['type']==0){
            $playLogic = new PlayGoodsLogic();
            $play = $playLogic->getPlay($order['gp_id']);
            if($play['type']==0){
                $shop_id = $manager['shop_id'];
                $shopLogic = new ShopLogic();
                $can_cancel_playids = $shopLogic->getShopPlay($shop_id);
                $can_cancel_playids = array_column($can_cancel_playids,'play_id');
                if(!in_array($order['gp_id'],$can_cancel_playids)){
                    $this->error('200099',"您没有权限核销该订单");
                }
            }
        }
        $result = $orderLogic->cancelOrder($cancel_no,$this->user_id,$type,$cancel_num);
        if($result){
            $this->response();
        }else{
            $this->error('200003',"该订单已经不能再核销");
        }
    }

    /**
     * 手动核销卡券、提货、回收商品
     * @apiDescription   by Jim
     * @api              {post} /order/cancel-order-by-hand 手动核销卡券、提货、回收商品
     * @apiName          cancel-order-by-hand
     * @apiVersion       1.0.0
     * @apiParam {string} cancel_no 核销的订单no
     * @apiParam {string} access_token
     * @apiGroup         Order
     * @apiSampleRequest /order/cancel-order-by-hand?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {

    }
     * @apiError         200003 fail 200002 请登录店长账户进行核销
     */
    public function actionCancelOrderByHand(){
        $cancel_no = $this->getQueryparams('cancel_no','');
        $cancel_num = $this->getQueryparams('cancel_num',0);
        if(strlen($cancel_no)>8){
            $cancel_notemp = $cancel_no;
            $cancel_num = substr($cancel_notemp,8);
            $cancel_no = substr($cancel_no,0,8);
        }
        $userLogic = new UserLogic();
        $user = $userLogic->getUser($this->user_id);
        if($user->type!=2){
            $this->error('200002','请登录店长账户进行核销');
        }
        $manager = $userLogic->getManager($this->user_id);
        if($manager['on_work']!=1){
            $this->error('200009','您没有上班，不能核销');
        }
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderByCancelNo($cancel_no);
        if($order['type']==0){
            $playLogic = new PlayGoodsLogic();
            $play = $playLogic->getPlay($order['gp_id']);
            if($play['type']==0){
                $shop_id = $manager['shop_id'];
                $shopLogic = new ShopLogic();
                $can_cancel_playids = $shopLogic->getShopPlay($shop_id);
                $can_cancel_playids = array_column($can_cancel_playids,'play_id');
                if(!in_array($order['gp_id'],$can_cancel_playids)){
                    $this->error('200099',"您没有权限核销该订单");
                }
            }
        }
        $result = $orderLogic->cancelOrder($cancel_no,$this->user_id,-1,$cancel_num);
        if($result){
            $this->response($result);
        }else{
            $this->error('200003',"该订单不能核销");
        }
    }


    public function actionCancelOrderYoyo(){
        $cancel_num = $this->getQueryparams('cancel_num',0);
        $device_id = $this->getQueryparams('device_id',0);
        $userLogic = new UserLogic();
        /*$user = $userLogic->getUser($this->user_id);
        if($user->type!=2){
            $this->error('200002','请登录店长账户进行核销');
        }
        $manager = $userLogic->getManager($this->user_id);
        if($manager['on_work']!=1){
            $this->error('200009','您没有上班，不能核销');
        }*/

        $ordertemp = Order::find()
            ->from('{{%order}} o')
            ->leftJoin('{{%play}} p','p.play_id=o.gp_id')
            ->where("o.user_id=".$this->user_id." AND o.type=0 AND o.current_num>0 AND p.type=1 AND o.status!=0")
            ->orderBy('o.order_id')
            ->asArray()
            ->all();
       if(!$ordertemp){
           $this->error('2001001','儿媳币不值');
       }else{
           $cancel_no = $ordertemp[0]['cancel_no'];
       }

        $orderLogic = new OrderLogic();
        $shopLogic = new ShopLogic();
        $order = $orderLogic->getOrderByCancelNo($cancel_no);
        $deviceLogic = new DeviceLogic();
        $device = $deviceLogic->getDeviceById($device_id);
        $manager = $shopLogic->getManager($device['shop_id']);
        if(!$manager){
            $this->error('2001009','此设备暂时无法使用在线支付');
        }
        //if($order['type']==3){
            $user_id = $manager['user_id'];
        /*}else{
            $this->error('200100',"error");
        }*/
        $result = $orderLogic->cancelOrder($cancel_no,$user_id,-1,$cancel_num,1);
        if($result){

            $httpCurl = new HttpCurl();
            $res= $httpCurl->yoyoget('/mafu/event/launch_pulse_signal_deivce',['imei'=>$device['device_imei'],'high'=>$device['device_high'],'low'=>$device['device_low'],'pulse'=>$cancel_num]);
            file_put_contents(date("Ymd").".txt", json_encode($res)." 日期：".date("Y-m-d H:i:s",time()).PHP_EOL,FILE_APPEND);
            $this->response($result);
        }else{
            $this->error('200003',"该订单不能核销");
        }
    }




    /**
     * 购买和充值记录
     * @apiDescription   by Jim
     * @api              {post} /order/get-order-list 购买和充值记录
     * @apiName          get-order-list
     * @apiVersion       1.0.0
     * @apiParam {int} type 0体验券和玩具，1充值
     * @apiParam {string} access_token
     * @apiGroup         Order
     * @apiSampleRequest /order/get-order-list?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * [{
    `order_id` int(11) NOT NULL AUTO_INCREMENT,
    `order_no` varchar(255) NOT NULL COMMENT '订单编号',（二维码编号）
    `type` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '订单类型：默认0，play类型，1,goods类型',
    `status` 订单状态：0未支付,1.待使用，2待提货 3,待回收，4.使用中,5已使用，6已完成，7已过期',
    `gp_id` int(11) unsigned NOT NULL COMMENT '商品或者体验券id',
    `current_num` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '体验卡或者体验券当前有效次数，商品为0，体验券为0或者1，体验卡为0+',（体验卡要调用具体的play时里面的值）
    `order_time` datetime NOT NULL COMMENT '下单时间',
    `pay_time` datetime DEFAULT NULL COMMENT '支付时间',
    `expire_time` date NOT NULL COMMENT '有效时间',
    `user_id` int(11) unsigned NOT NULL COMMENT ' 购买用户id',
    `shop_id` int(11) unsigned DEFAULT NULL COMMENT '自提点商店',
     * `price` decimal(10,2) unsigned NOT NULL, 价格
    goods_name(play_name)商品名或者卡券名，通过type判断
     *
     * 以下为type为1才有的值
     * category 0为充值，1为回收 2为系统
     * title 标题

    }]
     * @apiError         none
     */
    public function actionGetOrderList(){
        $type = $this->getQueryparams('type',0);//0体验券和玩具，1充值
        $orderLogic = new OrderLogic();
        $order_list = $orderLogic->getOrderList($this->user_id,$type);
        //var_dump($order_list);exit;
        foreach($order_list AS $key=>&$value){
            if($type==0){
                if($value['status']==4){
                    if($value['type']==0){
                        $value['status'] = 5;
                    }else{
                        $value['status'] = 6;
                    }
                }
                if($value['status']==3){
                    $value['status'] = 4;
                }
                if($value['status']==2){
                    $value['status'] = 3;
                }
                if($value['status']==1){
                    if($value['type']==1){
                        $value['status'] = 2;
                    }
                }
                if(in_array($value['status'],[1,2,3,4]) && $value['expire_time']<date('Y-m-d')){
                    $value['status'] = 7;
                }

                if($value['status']==5 || $value['status']==6){
                    $value['cancel_time'] = date('Y-m-d',strtotime($value['cancel_time']));
                }

                if($value['type']==2){
                    $value['status'] = 5;
                }

            }else{
                $value['category'] = 0;
                $value['title'] = $value['play_name'];
                if($value['ext_goods_id']){
                    $value['category'] = 1;
                    $goods = Goods::findOne(['goods_id'=>$value['ext_goods_id']]);
                    $value['title'] = $goods->goods_name;
                }elseif($value['remark']){
                    $value['category'] = 2;
                    $value['title'] = $value['remark'];
                }
            }
        }
        $this->response($order_list);
    }
    /**
     * 使用记录
     * @apiDescription   by Jim
     * @api              {post} /order/get-cancel-list 使用记录
     * @apiName          get-cancel-list
     * @apiVersion       1.0.0
     * @apiParam {string} access_token
     * @apiGroup         Order
     * @apiSampleRequest /order/get-cancel-list?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * [{
    `cancel_id` int(11) NOT NULL AUTO_INCREMENT,
    `order_id` int(11) unsigned NOT NULL,
    `manager_id` int(11) unsigned NOT NULL COMMENT '店长id',
    `shop_id` int(11) unsigned NOT NULL COMMENT '核销或者回收的商店',
    `type` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '类型：默认0为核销体验券，1为核销体验卡，2为提货商品，3为回收商品',
    `cancel_time` datetime NOT NULL COMMENT '核销或回收时间',
     *shop_name 商店名


    }]
     * @apiError        none
     */
    public function actionGetCancelList(){
        $orderLogic = new OrderLogic();
        $cancel_list = $orderLogic->getCancelList($this->user_id);
        $this->response($cancel_list);
    }
    /**
     * 订单管理
     * @apiDescription   by Jim
     * @api              {post} /order/get-order-list-by-manager 订单管理
     * @apiName          get-order-list-by-manager
     * @apiVersion       1.0.0
     * @apiParam {int} type -1全部 0卡券 1商品
     * @apiParam {string} access_token
     * @apiGroup         Order
     * @apiSampleRequest /order/get-order-list-by-manager?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * [
    {
    "order_id": "4",
    "order_no": "A426134625760030",
    "type": null,
    "status": "1",
    "gp_id": "1",
    "current_num": "0",
    "order_time": "2018-04-26 11:31:02",
    "pay_time": "2018-04-26 14:10:12",
    "expire_time": null,
    "user_id": "3",
    "shop_id": "1",
    "price": null,
    "ext_goods_id": null,
    "remark": null,
    "play_id": "3",
    "play_name": null,
    "num": null,
    "goods_id": "1",
    "goods_name": "商品1",
    "real_price": "50.00",
    "price": "50.00",
    "recovery_num": "10",
    "goods_pic": "/default_goods.jpg",
    "goods_pics": "/default_goods_1.jpg,/default_goods_2.jpg",
    "summary": "test",
    "effective_days": "30",
    "age": "6岁以下",
    "model": "SN_001",
    "description": "test",
    "phone": "18664699096"
    },
    {
    "order_id": "1",
    "order_no": "A426119480250062",
    "type": "0",
    "status": null,
    "gp_id": "1",
    "current_num": "1",
    "order_time": "2018-04-26 11:05:48",
    "pay_time": null,
    "expire_time": "30",
    "user_id": "3",
    "shop_id": null,
    "price": "20.00",
    "ext_goods_id": null,
    "remark": null,
    "play_id": null,
    "play_name": "一人畅玩",
    "num": "1",
    "goods_id": null,
    "goods_name": null,
    "real_price": null,
    "price": null,
    "recovery_num": null,
    "goods_pic": null,
    "goods_pics": null,
    "summary": null,
    "effective_days": null,
    "age": null,
    "model": null,
    "description": null,
    "phone": "18664699096"
    }
    ]
     * @apiError        none
     */
    public function actionGetOrderListByManager(){
        //$shop_id = $this->getQueryparams('shop_id',0);
        $type = $this->getQueryparams('type',-1);
        $orderLogic = new OrderLogic();
        $pgLogic = new PlayGoodsLogic();
        $order_list = $orderLogic->getOrderListByManager($this->user_id,$type);
        foreach($order_list AS $key=>&$value){
            //$value['expire_time'] = date('Y-m-d',strtotime($value['pay_time']))." -- ".$value['expire_date'];
            if($value['order_type']==0){
                $play = $pgLogic->getPlay($value['gp_id']);
                if($play['type']==1){
                    $value['is_card'] = 1;
                    $value['play_name'] = "嬉游币";
                }else{
                    $value['is_card'] = 0;
                    $value['play_name'] = $play['play_name'];
                }
                $value['play_pic'] = $play['play_pic'];

            }elseif($value['order_type']==2){
                $value['type'] = 2;
                $deviceLogic = new DeviceLogic();
                $device = $deviceLogic->getDeviceById($value['gp_id']);
                $value['device_pic'] = $device['device_pic'];
                $value['device_name'] = $device['device_name'];
            }else{
                $goods = $pgLogic->getGoods($value['gp_id']);
                $value['is_card'] = 0;
                $value['goods_pic'] = $goods['goods_pic'];
                $value['goods_name'] = $goods['goods_name'];
            }
        }
        $this->response($order_list);
    }


    /**
     * 店铺数据统计
     * @apiDescription   by Jim
     * @api              {post} /order/get-cancel-count 店铺数据统计
     * @apiName          get-cancel-count
     * @apiVersion       1.0.0
     * @apiParam {int} shop_id
     * @apiParam {string} cancel_time '2018-06'
     * @apiGroup         Order
     * @apiSampleRequest /order/get-cancel-count?flagsign=1
     * @apiSuccessExample {json} 获取成功
     {
     "total": 158,  总收入
    "experience_total": 8, 体验收入
    "sale_total": 150, 销售收入
    "recovery_total": 0, 回收收入
    "recharge_total": 0, 充值收入
      }
     * @apiError        none
     */
    public function actionGetCancelCount(){
        $shop_id = $this->getQueryparams('shop_id',0);
        $cancel_time = $this->getQueryparams('cancel_time',date('Y-m'));
        $start_time = date('Y-m-01 00:00:00',strtotime($cancel_time.'-01 00:00:00'));
        $start_time_temp = date('Y-m-d',strtotime($start_time));
        $end_time = date('Y-m-d 23:59:59', strtotime("$start_time_temp +1 month -1 day"));
        $orderLogic = new OrderLogic();
        $list = $orderLogic->getIncomeByShop($shop_id,$start_time,$end_time);
        $total = 0;
        $experience_total = 0;
        $sale_total = 0;
        $recovery_total = 0;
        $recharge_total = 0;
        $yoyo_total = 0;
        foreach($list AS $key=>$value){
            $total += $value['total_commission'];
            if($value['type']==0){
                $experience_total += $value['total_commission'];
            }elseif($value['type']==1){
                $recharge_total += $value['total_commission'];
            }elseif($value['type']==2){
                $sale_total += $value['total_commission'];
            }elseif($value['type']==3){
                $recovery_total += $value['total_commission'];
            }else{
                $yoyo_total += $value['total_commission'];
            }
        }
        $this->response(['total'=>$total,'experience_total'=>$experience_total,'recharge_total'=>$recharge_total,'sale_total'=>$sale_total,'recovery_total'=>$recovery_total,'yoyo_total'=>$yoyo_total]);
    }



    /**
     * 收入明细和数据统计
     * @apiDescription   by Jim
     * @api              {post} /order/get-cancel-list-by-myself 收入明细和数据统计
     * @apiName          get-cancel-list-by-myself
     * @apiVersion       1.0.0
     * @apiParam {string} access_token
     * @apiParam {string} cancel_time ‘2018-04’
     * @apiGroup         Order
     * @apiSampleRequest /order/get-cancel-list-by-myself?flagsign=1
     * @apiSuccessExample {json} 获取成功

    "total": 158,
    "experience_total": 8,
    "sale_total": 150,
    "recovery_total": 0,
    "recharge_total": 0,
    "list": [
    {
    "cancel_id": "1",
    "order_id": "4",
    "manager_id": "1",
    "shop_id": "1",
    "type": null,
    "cancel_time": "2018-04-26 15:47:37",
    "order_no": "A426134625760030",
    "status": "1",
    "gp_id": "1",
    "current_num": "0",
    "order_time": "2018-04-26 11:31:02",
    "pay_time": "2018-04-26 14:10:12",
    "expire_time": null,
    "user_id": "3",
    "price": "50.00",
    "ext_goods_id": null,
    "remark": null,
    "phone": "18664699096",
    "play_id": "3",
    "play_name": null,
    "num": null,
    "goods_id": "1",
    "goods_name": "商品1",
    "real_price": "50.00",
    "recovery_num": "10",
    "goods_pic": "/default_goods.jpg",
    "goods_pics": "/default_goods_1.jpg,/default_goods_2.jpg",
    "summary": "test",
    "effective_days": "30",
    "age": "6岁以下",
    "model": "SN_001",
    "description": "test",
    "cancel_type": "2",
    "order_type": "1",
    "commission": 10
    },
    {
    "cancel_id": "2",
    "order_id": "4",
    "manager_id": "1",
    "shop_id": "1",
    "type": null,
    "cancel_time": "2018-04-26 15:48:52",
    "order_no": "A426134625760030",
    "status": "1",
    "gp_id": "1",
    "current_num": "0",
    "order_time": "2018-04-26 11:31:02",
    "pay_time": "2018-04-26 14:10:12",
    "expire_time": null,
    "user_id": "3",
    "price": "50.00",
    "ext_goods_id": null,
    "remark": null,
    "phone": "18664699096",
    "play_id": "3",
    "play_name": null,
    "num": null,
    "goods_id": "1",
    "goods_name": "商品1",
    "real_price": "50.00",
    "recovery_num": "10",
    "goods_pic": "/default_goods.jpg",
    "goods_pics": "/default_goods_1.jpg,/default_goods_2.jpg",
    "summary": "test",
    "effective_days": "30",
    "age": "6岁以下",
    "model": "SN_001",
    "description": "test",
    "cancel_type": "2",
    "order_type": "1",
    "commission": 10
    },
    {
    "cancel_id": "3",
    "order_id": "4",
    "manager_id": "1",
    "shop_id": "1",
    "type": null,
    "cancel_time": "2018-04-26 16:01:23",
    "order_no": "A426134625760030",
    "status": "1",
    "gp_id": "1",
    "current_num": "0",
    "order_time": "2018-04-26 11:31:02",
    "pay_time": "2018-04-26 14:10:12",
    "expire_time": null,
    "user_id": "3",
    "price": "50.00",
    "ext_goods_id": null,
    "remark": null,
    "phone": "18664699096",
    "play_id": "3",
    "play_name": null,
    "num": null,
    "goods_id": "1",
    "goods_name": "商品1",
    "real_price": "50.00",
    "recovery_num": "10",
    "goods_pic": "/default_goods.jpg",
    "goods_pics": "/default_goods_1.jpg,/default_goods_2.jpg",
    "summary": "test",
    "effective_days": "30",
    "age": "6岁以下",
    "model": "SN_001",
    "description": "test",
    "cancel_type": "2",
    "order_type": "1",
    "commission": 10
    },
    {
    "cancel_id": "4",
    "order_id": "4",
    "manager_id": "1",
    "shop_id": "1",
    "type": null,
    "cancel_time": "2018-04-26 16:11:32",
    "order_no": "A426134625760030",
    "status": "1",
    "gp_id": "1",
    "current_num": "0",
    "order_time": "2018-04-26 11:31:02",
    "pay_time": "2018-04-26 14:10:12",
    "expire_time": null,
    "user_id": "3",
    "price": "50.00",
    "ext_goods_id": null,
    "remark": null,
    "phone": "18664699096",
    "play_id": "3",
    "play_name": null,
    "num": null,
    "goods_id": "1",
    "goods_name": "商品1",
    "real_price": "50.00",
    "recovery_num": "10",
    "goods_pic": "/default_goods.jpg",
    "goods_pics": "/default_goods_1.jpg,/default_goods_2.jpg",
    "summary": "test",
    "effective_days": "30",
    "age": "6岁以下",
    "model": "SN_001",
    "description": "test",
    "cancel_type": "2",
    "order_type": "1",
    "commission": 10
    },
    {
    "cancel_id": "5",
    "order_id": "4",
    "manager_id": "1",
    "shop_id": "1",
    "type": null,
    "cancel_time": "2018-04-26 16:14:13",
    "order_no": "A426134625760030",
    "status": "1",
    "gp_id": "1",
    "current_num": "0",
    "order_time": "2018-04-26 11:31:02",
    "pay_time": "2018-04-26 14:10:12",
    "expire_time": null,
    "user_id": "3",
    "price": "50.00",
    "ext_goods_id": null,
    "remark": null,
    "phone": "18664699096",
    "play_id": "3",
    "play_name": null,
    "num": null,
    "goods_id": "1",
    "goods_name": "商品1",
    "real_price": "50.00",
    "recovery_num": "10",
    "goods_pic": "/default_goods.jpg",
    "goods_pics": "/default_goods_1.jpg,/default_goods_2.jpg",
    "summary": "test",
    "effective_days": "30",
    "age": "6岁以下",
    "model": "SN_001",
    "description": "test",
    "cancel_type": "2",
    "order_type": "1",
    "commission": 10
    },
    {
    "cancel_id": "8",
    "order_id": "1",
    "manager_id": "1",
    "shop_id": null,
    "type": "0",
    "cancel_time": "2018-04-27 00:12:11",
    "order_no": "A426119480250062",
    "status": null,
    "gp_id": "1",
    "current_num": "1",
    "order_time": "2018-04-26 11:05:48",
    "pay_time": "2018-04-30 00:04:02",
    "expire_time": "30",
    "user_id": "3",
    "price": "20.00",
    "ext_goods_id": null,
    "remark": null,
    "phone": "18664699096",
    "play_id": null,
    "play_name": "一人畅玩",
    "num": "1",
    "goods_id": null,
    "goods_name": null,
    "real_price": null,
    "recovery_num": null,
    "goods_pic": null,
    "goods_pics": null,
    "summary": null,
    "effective_days": null,
    "age": null,
    "model": null,
    "description": null,
    "cancel_type": "0",
    "order_type": "0",
    "commission": 8
    }
    ]
    }
     * @apiError        none
     */
    public function actionGetCancelListByMyself(){
        $shop_id = $this->getQueryparams('shop_id',0);
        $cancel_time = $this->getQueryparams('cancel_time',date('Y-m'));
        $start_time = date('Y-m-01 00:00:00',strtotime($cancel_time.'-01 00:00:00'));
        $start_time_temp = date('Y-m-d',strtotime($start_time));
        $end_time = date('Y-m-d 23:59:59', strtotime("$start_time_temp +1 month -1 day"));
        $userLogic = new UserLogic();
        $user = $userLogic->getUser($this->user_id);
        $orderLogic = new OrderLogic();
        /*$commissionConfig = $orderLogic->getCommissionConfig();
        $commissionConfigTemp = [];
        foreach($commissionConfig AS $k=>$v){
            $config_ext = json_decode($v['config_ext'],true);
            $commissionConfigTemp[(string)$config_ext['role']][(string)$config_ext['type']] = $v['config_value'];
        }*/
        $total = 0;
        $experience_total = 0;
        $sale_total = 0;
        $recovery_total = 0;
        $recharge_total = 0;
        $yoyo_total = 0;
        if($user->type==1){
            $shopLogic = new ShopLogic();
            //$shops = $shopLogic->getShopListByOwner($this->user_id);
            //$shop_ids = array_column($shops,'shop_id');
            $cancel_list = $orderLogic->getCancelListAndIncomeByMyself($this->user_id,$shop_id,$start_time,$end_time,$user->type);
            foreach($cancel_list AS $key=>&$value){
                if($value['ptype']==1){
                    $value['play_name'] = '嬉游通';
                }
                if($value['commission']===null){
                    array_splice($cancel_list, $key, 1);
                    continue;
                }
                $total += $value['commission'];
                if($value['cancel_type']==0){
                    $experience_total += $value['commission'];
                }elseif($value['cancel_type']==1){
                    $recharge_total += $value['commission'];
                }elseif($value['cancel_type']==2){
                    $sale_total += $value['commission'];
                }elseif($value['cancel_type']==3){
                    $recovery_total += $value['commission'];
                }elseif($value['cancel_type']==4){
                    $yoyo_total += $value['commission'];
                }

            }

        }else{
            $cancel_list = $orderLogic->getCancelListAndIncomeByMyself($this->user_id,0,$start_time,$end_time,$user->type);
            foreach($cancel_list AS $key=>&$value){
                if($value['ptype']==1){
                    $value['play_name'] = '嬉游通';
                }
                if($value['commission']===null){
                    array_splice($cancel_list, $key, 1);
                    continue;
                }
                $total += $value['commission'];
                if($value['cancel_type']==0){
                    $experience_total += $value['commission'];
                }elseif($value['cancel_type']==1){
                    $recharge_total += $value['commission'];
                }elseif($value['cancel_type']==2){
                    $sale_total += $value['commission'];
                }elseif($value['cancel_type']==3){
                    $recovery_total += $value['commission'];
                }elseif($value['cancel_type']==4){
                    $yoyo_total += $value['commission'];
                }
            }
        }
        $this->response(['total'=>$total,'experience_total'=>$experience_total,'sale_total'=>$sale_total,'recovery_total'=>$recovery_total,'recharge_total'=>$recharge_total,'yoyo_total'=>$yoyo_total,'list'=>$cancel_list]);
    }

    public function actionCheckCode(){
        $cancel_no = $this->getQueryparams('cancel_no','');
        $orderLogic = new OrderLogic();
        if(strlen($cancel_no)>8){
            $cancel_notemp = $cancel_no;
            $cancel_num = substr($cancel_notemp,8);
            $cancel_no = substr($cancel_no,0,8);
        }else{
            $cancel_num = 1;
        }
        $code = $orderLogic->findOrderByCancelNo($cancel_no);
        if($code){
            $this->response(['order_no'=>$code->order_no,'num'=>$cancel_num]);
        }else{
            $this->error('80001','核销码有误，请检查后重新输入');
        }
    }



}
